<template>
	<view>
		<!-- 顶部的搜索栏 -->
		<view class="search-wrapper">
			<view class="search-input">
				<icon type="search" size="16"/>
				<!-- 输入框 -->
				<input v-model="inputValue" placeholder="输入商品名称" @confirm="handleSearch"/>
				<!-- inputValue有值就是显示该图标，没有值就隐藏 -->
				<icon type="clear" size="16" v-if="inputValue" @click="handleClear"/>
			</view>
			<button type="warn" @click="handleSearch">搜索</button>
		</view>
		
		<!-- 商品列表 -->
		<view class="goods-list">
			<navigator class="goods-item" 
			:url="`/pages/goods_detail/index?goods_id=${item.goods_id}`"
			v-for="(item, index) in list"
			:key="index">
				<!-- <image src="https://img11.360buyimg.com/seckillcms/s280x280_jfs/t1/135781/15/13856/200437/5f9a8ad9E008da1e0/38287dfb69f11f2f.jpg.webp" mode="aspectFill"></image> -->
				<view class="goods-title">
					{{item.goods_name}}
				</view>
			</navigator>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 输入框的值
				inputValue: "",
				// list保存的搜索的推荐商品
				list: [],
				// 是否需要请求的开关
				isRequest: true,
				timer: null
			}
		},
		watch: {
			// 监听输入框值的变化
			inputValue(newValue, oldValue){
				// 值为空就直接返回
				if(this.inputValue.trim() === "") {
					this.list = [];
					return;
				}
				// 清楚定时器
				clearTimeout(this.timer);
				// 1秒后开启定时器
				this.timer = setTimeout(() => {	
					// 如果值不相等，说明用户还在输入，所以不用请求
					if(oldValue.trim() === newValue.trim()) return;
					
					// 请求搜索建议商品
					uni.request({
						url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch",
						data: {
							query: this.inputValue
						},
						success: res => {
							const {message} = res.data;
							// message就是商品列表
							this.list = message;
						}
					})
				}, 1000)
			}
		},
		methods: {
			// 清空输入框的值
			handleClear(){
				this.inputValue = "";
			},
			
			// 跳转到商品列表
			handleSearch(){
				uni.navigateTo({
					// 跳转到商品列表页，并且带上搜索关键字
					url: "/pages/goods_list/index?keyword=" + this.inputValue
				});
			}
		}
	}
</script>

<style lang="less">
	.search-wrapper{
		padding: 20rpx;
		display: flex;
		
		.search-input{
			flex: 1;
			background: #eee;
			height: 61rpx;
			padding: 0 20rpx;
			margin-right: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 50px;
			
			input{
				flex: 1;
				padding: 0 5px;
				font-size: 14px;
			}
		}
		
		button{
			height: 61rpx;
			line-height: 61rpx;
			font-size: 14px;
		}
	}
	
	.goods-list{
		padding: 0 20rpx;
		
		.goods-item{
			padding: 30rpx 0;
			border-bottom: 1px #eee solid;
			display: flex;
			
			image{
				width: 191rpx;
				height: 191rpx;
				display: block;
				margin-right: 20rpx;
				flex-shrink: 0;
			}
			
			.goods-title{
				flex: 1;
				font-size: 14px;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				align-self: flex-start;
			}
		}
	}
</style>
